package com.lr.safety.studyenglish;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import es.dmoral.toasty.Toasty;

public class MainActivity extends AppCompatActivity {

    private Button mSearchBtn;
    private EditText mSearchContentEt;
    private TextView mContentTv;
    private Button mPlayBtn;
    private String mPlaySource = "";
    private MediaPlayer mp;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JsonRootBean bean = (JsonRootBean) msg.obj;
            List<Trans_result> results = bean.getTrans_result();
            if (results != null && results.size() > 0 && results.get(0).getSrc() != null) {
                mContentTv.setText("原文：" + results.get(0).getSrc() + "\n" + "翻译：" + results.get(0).getDst());
                mPlaySource = results.get(0).getDst();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_main);
        init();
        listen();
    }

    void init() {
        mPlayBtn = (Button) findViewById(R.id.play_btn);
        mSearchBtn = (Button) findViewById(R.id.search_btn);
        mSearchContentEt = (EditText) findViewById(R.id.search_et);
        mContentTv = (TextView) findViewById(R.id.content_tv);
    }

    void listen() {
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String search = mSearchContentEt.getText().toString().trim();
                if (!search.equals("")) {
                    preparePlayMedia();
                    Toasty.info(MainActivity.this, "正在翻译中..").show();
                    switch (search) {
                        case "startup":
                        case "start up":
                            mContentTv.setText("原文：P: Maiquetia Tower Argentina 100 stand K15, request start up and push back. Information M. Our slot-time is 1510 plus 6 minutes.\n" +
                                    "C: Argentina100 start up and push back at 55." + "\n" + "翻译：开车");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.start_up);
                            mp.start();
                            break;
                        case "taxiinstructions":
                        case "taxi instructions":
                            mContentTv.setText("原文：P: Ground Caledonian211 stand C8 request taxi to holding point for runway 27.\n" +
                                    "C: Caledonian211 taxi to holding point X runway 27." + "\n" + "翻译：滑跑指令");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.taxi_instructions);
                            mp.start();
                            break;
                        case "takeoff":
                        case "take off":
                            mContentTv.setText("原文：C: LAB808 report when ready for departure.\n" +
                                    "P: Ready for departure LAB808.\n" +
                                    "C: LAB808 behind Boeing 727 on short final line up behind.\n" +
                                    "P: Behind Boeing 727 on final, lining up LAB808.\n" +
                                    "C: Correct LAB808.\n" + "\n" + "翻译：起飞");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.take_off);
                            mp.start();
                            break;
                        case "weatherinformation":
                        case "weather information":
                            mContentTv.setText("原文：RADAR: JY-AEX Baghdad Control, you have unknown traffic at 2 o’clock 5 miles crossing from right to left.\n" +
                                    "  P: Looking out JY-AEX. Request vectors.\n" +
                                    "  RADAR: J-EX avoiding action. Turn right 30 degrees immediately and report heading\n" +
                                    "  P: Turning right 30 degrees. New heading is 090 J-EX\n" +
                                    "  RADAR: J-EX now clear of traffic. Resume own navigation to Samrra Baghdad Control\n" + "\n" + "翻译：天气信息");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.weather_information);
                            mp.start();
                            break;
                        case "positionreporting":
                        case "position reporting":
                            mContentTv.setText("原文：P: Los Angeles Control N191TX over Daggetts at 30 fl330 estimating San Bernadino at 02 05\n" +
                                    "  C: N191TX Los Angeles Control roger. Maintain present level omit position reports until San Bernadino\n" + "\n" + "翻译：位置");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.position_reporting);
                            mp.start();
                            break;
                        case "enrouteholdinginstructions":
                        case "en route holdin instructions":
                            mContentTv.setText("原文：C: N243AX Santa Barbara Control\n" +
                                    "P: Santa Barbara N243AX\n" +
                                    "C: N-3AX maintain fl290 and hold at Edsel. Expect further clearance at 20\n" +
                                    "P: N-3AX maintaining fl290 and holding at Edsel\n" + "\n" + "翻译：航路等待指示");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.en_route_holdinginstructions);
                            mp.start();
                            break;
                        case "descentinstruction":
                        case "descent instruction":
                            mContentTv.setText("原文：P: Los Angeles Control BAW505 passing Edsel at fl210, request descent at 1705\n" +
                                    "  C: BAW505 Los Angeles Control descend immediately to fl120. Report passing fl150\n" +
                                    "  P: BAW505 leaving fl210 for fl120. Report passing fl150\n" + "\n" + "翻译：下降指示");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.descent_instruction);
                            mp.start();
                            break;
                        case "taxiinstructionsafterlanding":
                        case "taxi instructions after landing":
                            mContentTv.setText("原文：P: Narita Ground Cathay 50 runway vacated\n" +
                                    "  C: Cathay 50 turn left onto taxiway A4, proceed to P3, parking stand 31\n" +
                                    "  P: Via A4 to P3, stand 31 Cathay 50\n" + "\n" + "翻译：落地后滑跑");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.taxi_instructions_afterlanding);
                            mp.start();
                            break;
                        case "landinginstructions":
                        case "landing instructions":
                            mContentTv.setText("原文：P: Malindi Tower 5-CD aerodrome in sight, request straight-in-approach on runway 35.\n" +
                                    "  C: 5-CD cleared straight-in-approach runway 35. Wind calm. Temperature 27 QFE 1002. Report final.\n" + "\n" + "翻译：落地指令");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.landing_instructions);
                            mp.start();
                            break;
                        case "initialapproachclearance":
                        case "initial approach clearance":
                            mContentTv.setText("原文：P: Narita Arrival Japanair 431 heavy with B\n" +
                                    "  C: Japanair 431 Narita maintain fl100 cleared to Onjuku, Standard Jupiter One arrival. After passing Onjuku, descend to 8000ft QNH992. Number 3 in traffic. No delay expected, present information is C. Visibility 6km in haze.\n" +
                                    "  P: Narita Japanair 431 Standard Jupiter One arrival. After passing Onjuku cleared to leave fl100 for 8000ft QNH992 Japanair431.\n" +
                                    "  C: Japanair431 correct. Squawk 5616 ident.\n" + "\n" + "翻译：开始进近许可");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.initial_approachclearance);
                            mp.start();
                            break;
                        case "landingclearance":
                        case "landing clearance":
                            mContentTv.setText("原文：P: Narita Tower Cathay 50 is fully established, runway 16\n" +
                                    "C: Cathay 50 report passing outer marker. QFE 1010 wind 180° 15knots\n" +
                                    "P: Report passing outer marker QFE1010, Cathay 50\n" +
                                    "(later)\n" +
                                    "P: Outer marker Cathay 50\n" +
                                    "C: Cathay 50 continue approach, one DC-10 to depart\n" +
                                    "P: Continue approach Cathay50\n" +
                                    "(later)\n" +
                                    "C: Cathay 50 cleared to land\n" +
                                    "P: Cleared to land Cathay 50\n" +
                                    "(later)\n" +
                                    "C: Cathay 50 Landing-time 23. Take first right and contact Ground on 121.8 when vacated.\n" + "\n" + "翻译：落地许可");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.landing_clearance);
                            mp.start();
                            break;
                        case "goaround":
                        case "go around":
                            mContentTv.setText("原文：P: Tower Koreanair 001 out marker\n" +
                                    "  C: Koreanair 001 runway is blocked. Go around immediately, I say again go around\n" +
                                    "  P: Koreanair 001 going around\n" +
                                    "  C: Koreanair 001 climb straight ahead to 3000ft QNH1009 and contact Approach on 125.8\n" +
                                    "  P: Koreanair 001 3000ft, contact Approach 125.8\n" + "\n" + "翻译：复飞");
                            mp = MediaPlayer.create(MainActivity.this, R.raw.go_round);
                            mp.start();
                            break;
                        default:
                            //如果没有专业词汇，则进行网络请求翻译
                            if (checkInput().equals("")) {
                                doWork("en", "zh");
                            } else {
                                doWork("zh", "en");
                            }
                            break;
                    }
                } else {
                    Toasty.info(MainActivity.this, "输入内容为空..").show();
                }
            }
        });
        mPlayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mPlaySource.equals("")) {
                    SpeechUtils.getInstance(MainActivity.this).speakText(mPlaySource);
                }
            }
        });
    }

    private String appid = "20180611000174760";
    private String appKey = "TSkxBAiMoTEx1c55qSXo";
    private HttpURLConnection conn;
    String qString = "";

    //翻译功能请求网络
    void doWork(final String from, final String to) {
        qString = mSearchContentEt.getText().toString().trim();
        //注意！与网络相关的操作要开启新的线程，不要早UI线程中进行，否则会出现
        //android.os.NetworkOnMainThreadException异常
        new Thread(new Runnable() {
            int salt = 123456;//随机数

            @Override
            public void run() {
                // TODO Auto-generated method stub
                String one = appid + qString + salt + appKey;
                try {
                    one = new String(one.getBytes("GBK"), "GBK");
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                URL url;
                try {
                    String md5 = stringToMD5(one);
                    url = new URL("http://api.fanyi.baidu.com/api/trans/vip/translate?" +
                            "q=" + qString + "&from=" + from + "&to=" + to + "&appid=" + appid + "&salt=" +
                            salt + "&sign=" + md5);
                    System.out.println(url);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(10000); // 连接的超时时间
                    conn.setReadTimeout(5000); // 读数据的超时时间
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        InputStream is = conn.getInputStream();
                        String state = getStringFromInputStream(is);
                        String result = decodeUnicode(state);
                        Gson gson = new Gson();
                        JsonRootBean bean = gson.fromJson(result, new TypeToken<JsonRootBean>() {
                        }.getType());
                        Message message = Message.obtain();
                        message.obj = bean;
                        mHandler.sendMessage(message);
                    } else {
                        Toasty.error(MainActivity.this, "网络连接失败...").show();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //流转字符串
    private String getStringFromInputStream(InputStream is) {
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //最好在将字节流转换为字符流的时候 进行转码
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = bf.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return buffer.toString();
    }

    //计算字符串的MD5值
    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    //Unicode编码转中文
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    outBuffer.append(aChar);
                }

            } else
                outBuffer.append(aChar);
        }
        return outBuffer.toString();
    }

    int isCnorEn(char c) {
        if (c >= 0x0391 && c <= 0xFFE5) //中文字符
            return 1;
        if (c >= 0x0000 && c <= 0x00FF) { //英文字符
            return 2;
        }
        return 3;
    }

    //判断输出中英文
    String checkInput() {
        String regex = "([a-zA-Z])";
        String str = mSearchContentEt.getText().toString().trim();
        String english = "";
        String chinese = "";
        english = str.replaceAll(regex, "").trim();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(english);
        while (m.find()) {
            english = m.group(1);
        }
        return english;
    }

    //播放前的准备工作，如果有音频正在播放，则停止，准备新的音频播放。
    void preparePlayMedia() {
        if (mp != null)
            if (mp.isPlaying()) {
                mp.stop();
            }
    }

    @Override
    protected void onDestroy() {
        //释放资源
        if (mp != null) {
            if (mp.isPlaying()) {
                mp.stop();
            }
            mp.release();
        }
        super.onDestroy();
    }
}
